<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2022/3/16
 * Time: 10:47
 */

namespace app\api\controller;


use pay\Ali;
use pay\Wxservicer;
use think\Db;

class Giftbag extends Base
{
    private $user_id; // 用户ID
    private $page; // 页码
    private $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    
    /**
     * 礼包列表
     * @return \think\response\Json
     * page      页码
     */
    public function giftBagList(){
        // 推荐礼包
        $recommendBag = Db::table('up_bo_giftbag')
            ->where(['gift_status' => 1, 'gift_is_recommend' => 1])
            ->field('gift_id, gift_name, gift_images, gift_price, gift_indate')
            ->find();
        if($recommendBag){
            if($recommendBag['gift_images']){
                $recommendBag['gift_images'] = explode(',', $recommendBag['gift_images']);
            }else{
                $recommendBag['gift_images'] = [];
            }
        }else{
            $recommendBag = [];
        }
       
        // 普通礼包
        $bag = Db::table('up_bo_giftbag')
            ->where(['gift_status' => 1, 'gift_is_recommend' => 2])
            ->field('gift_id, gift_name, gift_images, gift_price, gift_indate')
            ->page($this->page, 10)
            ->order('gift_time desc')
            ->select();
        if($bag){
            foreach($bag as $k => $v){
                if($v['gift_images']){
                    $bag[$k]['gift_images'] = explode(',', $v['gift_images']);
                }else{
                    $bag[$k]['gift_images'] = [];
                }
            }
        }else{
            $bag = [];
        }
        return json(['status' => 200, 'msg' => '', 'recommendBag' => $recommendBag, 'bag' => $bag]);
    }

    /**
     * 判断用户是否可以购买礼包
     * @return \think\response\Json
     * gift_id     礼包ID
     */
    public function canBuyGift(){
        $gift_id = input('gift_id');
        $can = $this->canBuy($gift_id);
        if($can == 0){
            $return = ['status' => 200, 'msg' => true];
        }elseif($can == 1){
            $return = ['status' => 0, 'msg' => '存在有效期内礼包，不可购买'];
        }else{
            $return = ['status' => 0, 'msg' => '已购买过该礼包，不可重复购买'];
        }
        return json($return);
    }

    //*************************=================   2022/12月改的需求 start =========================******************//
    /**
     * 礼包详情
     * @return \think\response\Json
     * gift_id      礼包ID
     */
    public function giftDetail(){
        $gift_id = input('gift_id');
        $detail = Db::table('up_bo_giftbag')
            ->where('gift_id', $gift_id)
            ->field('gift_id, gift_images, gift_name, gift_indate, gift_price, gift_status, gift_content, 
            gift_first_dec, gift_send_explain')
            ->find();
        if($detail['gift_status'] != 1) return json(['status' => 0, 'msg' => '礼包状态异常']);
        if($detail['gift_images']){
            $detail['gift_images'] = explode(',', $detail['gift_images']);
        }else{
            $detail['gift_images'] = [];
        }
        // 是否首次购买
        $isFirst = $this->firstBuy($gift_id); // 1 非首次    2 首次
        $detail['firstBuy'] = $isFirst;
        return json(['status' => 200, 'msg' => $detail]);
    }

    /**
     * 确认订单页面展示
     * @return \think\response\Json
     * gift_id      礼包ID
     */
    public function payShow(){
        $gift_id = input('gift_id');
        $gift = Db::table('up_bo_giftbag')
            ->where('gift_id', $gift_id)
            ->field('gift_thumb, gift_name, gift_price, gift_first_dec, gift_send_explain')
            ->find();
        // 快递
        $company = $this->expressCompany();
        $gift['company'] = $company;
        // 剩余积分&礼包邀请码
        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_giftbag_invite_other')->find();
        $gift['invite_other'] = $user['user_giftbag_invite_other'];
        // 是否首次购买
        $isFirst = $this->firstBuy($gift_id); // 1 非首次    2 首次
        $gift['firstBuy'] = $isFirst;
        return json(['status' => 200, 'msg' => $gift]);
    }

    /**
     * 确认订单
     * @return \think\response\Json
     * gift_id      礼包ID
     * addr_id      收货地址ID
     * order_remark    备注
     * pay_type      支付方式   1 积分  2 微信   3 支付宝
     */
    public function commitOrder(){
        $gift_id = input('gift_id');
        $addr_id = input('addr_id');
        $order_remark = input('order_remark');
        $invite_other = trim(input('invite_other'));
        $pay_type = input('pay_type');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);
        if(!$invite_other) return json(['status' => 0, 'msg' => '请输入邀请码']);
        if(!$addr_id) return json(['status' => 0, 'msg' => '请选择收货地址']);

        $gift = Db::table('up_bo_giftbag')
            ->where('gift_id', $gift_id)
            ->field('gift_price, gift_status, gift_indate, gift_first_dec, gift_is_zy')
            ->find();
        if($gift['gift_status'] != 1) return json(['status' => 0, 'msg' => '礼包状态异常']);

        $exist = Db::table('up_u_user')->where('user_invite', $invite_other)->find();
        if(!$exist) return json(['status' => 0, 'msg' => '请填写正确的邀请码']);
        if($invite_other != 'djl9988' && $exist['user_giftbag_level'] == 1){
            return json(['status' => 0, 'msg' => '无效的邀请码']);
        }

        if($gift['gift_is_zy'] == 1 && $exist['user_giftbag_level'] == 3){
            return json(['status' => 0, 'msg' => '您已是自由创业者，不可购买该礼包']);
        }

        $can = $this->canBuy($gift_id);
        if($can == 1){
            return json(['status' => 0, 'msg' => '存在有效期内礼包，不可购买']);
        }elseif($can == 2){
            return json(['status' => 0, 'msg' => '已购买过该礼包，不可重复购买']);
        }

        $mchid = Db::table('up_mchid')->where(['mch_default' => 1, 'mch_status' => 1])->find();
        if(!$mchid) return json(['status' => 0, 'msg' => '暂无可收款账户，请联系客服']);

        $order_number = 'BG_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
//        $indate = date('Y-m', strtotime("{$gift['gift_indate']} months"));

        $isFirst = $this->firstBuy($gift_id);
        if($isFirst == 1){ // 非首次
            $total_price = $gift['gift_price'];
            $dec_price = 0;
        }else{
            $total_price = round($gift['gift_price'] - $gift['gift_first_dec'], 2);
            $dec_price = $gift['gift_first_dec'];
        }

        $order = [
            'bog_number' => $order_number,
            'bog_user_id' => $this->user_id,
            'bog_gift_id' => $gift_id,
            'bog_total_price' => $total_price,
            'bog_dec_price' => $dec_price,
            'bog_remark' => $order_remark,
            'bog_addr_id' => $addr_id,
            'bog_pay_month' => date('Y-m'),
            'bog_indate' => date('Y-m'),
            'bog_indate_month' => $gift['gift_indate'],
            'bog_zeng_number' => $gift['gift_indate'] - 1,
            'bog_create_time' => $this->create_time,
            'bog_pay_type' => $pay_type,
            'bog_invite' => $invite_other
        ];


        Db::startTrans();
        try{
            // 插入订单
            $order_id = Db::table('up_bo_orderg')->insertGetId($order);

            if($pay_type == 3){
                // 调起支付宝支付
                $ali = new Ali(config('ali'));
                $return = $ali->getParam($order_number, $total_price, '礼包', '购买礼包');
            }else{
                // 调起微信支付
                $wxConfig = config('wechat_servicer');
                $wxConfig['sub_mchid'] = $mchid['mch_code'];
                $wx = new Wxservicer($wxConfig);
                $return = $wx->WeChatPayReadyServicerV2($total_price, $order_number, '购买礼包');
            }
            if($return['status'] == 200){
                Db::commit();
                return json(['status' => 200, 'msg' => $return['message'], 'order_id' => $order_id, 'price' => $total_price]);
            }else{
                Db::rollback();
                return json(['status' => 0, 'msg' => $return['message']]);
            }

        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 线上支付
     * @return \think\response\Json
     * order_id     订单ID
     * pay_type     支付方式   1 积分   2 微信   3 支付宝
     */
    public function payOrderOnline(){
        $order_id = input('order_id');
        $pay_type = input('pay_type');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);

        $order = Db::table('up_bo_orderg')
            ->join('up_bo_giftbag', 'bog_gift_id = gift_id', 'LEFT')
            ->where('bog_id', $order_id)
            ->field('bog_gift_id, bog_total_price, bog_status, gift_status, bog_number, bog_dec_price, 
            bog_user_id, gift_is_zy')
            ->find();

        if($order['bog_status'] != 1) return json(['status' => 0, 'msg' => '订单状态异常']);
        if($order['gift_status'] != 1) return json(['status' => 0, 'msg' => '礼包状态异常']);

        $can = $this->canBuy($order['bog_gift_id']);
        if($can == 1){
            return json(['status' => 0, 'msg' => '存在有效期内礼包，不可购买']);
        }elseif($can == 2){
            return json(['status' => 0, 'msg' => '已购买过该礼包，不可重复购买']);
        }

        $user = Db::table('up_u_user')->where('user_id', $order['bog_user_id'])->field('user_giftbag_level')->find();
        if($order['gift_is_zy'] == 1 && $user['user_giftbag_level'] == 3){
            return json(['status' => 0, 'msg' => '您已是自由创业者，不可购买该礼包']);
        }

        $mchid = Db::table('up_mchid')->where(['mch_default' => 1, 'mch_status' => 1])->find();
        if(!$mchid) return json(['status' => 0, 'msg' => '暂无可收款账户，请联系客服']);

        $order_number = 'BG_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        Db::startTrans();
        try{
            Db::table('up_bo_orderg')->update([
                'bog_id' => $order_id,
                'bog_pay_type' => $pay_type,
                'bog_updatetime' => $this->create_time,
                'bog_number' => $order_number
            ]);

            if($pay_type == 2){
                // 调起微信支付
                $wxConfig = config('wechat_servicer');
                $wxConfig['sub_mchid'] = $mchid['mch_code'];
                $wx = new Wxservicer($wxConfig);
                $return = $wx->WeChatPayReadyServicerV2($order['bog_total_price'], $order_number, '购买礼包');
            }else{
                // 调起支付宝支付
                $ali = new Ali(config('ali'));
                $return = $ali->getParam($order_number, $order['bog_total_price'], '礼包', '购买礼包');
            }
            if($return['status'] == 200){
                Db::commit();
                return json(['status' => 200, 'msg' => $return['message'], 'order_id' => $order_id, 'price' => $order['bog_total_price']]);
            }else{
                Db::rollback();
                return json(['status' => 0, 'msg' => $return['message']]);
            }
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }

    }

    //*************************=================   2022/12月改的需求 end =========================******************//

    
    //***************************************************  礼包中心--我的礼包团队
    /**
     * 我的礼包团队---礼包中心
     * @return \think\response\Json
     */
    public function myTeamList(){
        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_invite')->find();
        if($user['user_invite']){
            $teamList = $this->myTeam(1, $user['user_invite']);
        }else{
            $teamList = 0;
        }
        if($teamList){
            return json(['status' => 200, 'msg' => $teamList]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 我的礼包团队队员信息---礼包中心
     * @return \think\response\Json
     * other_user_id     下级用户ID
     */
    public function otherUserFy(){
        $other_user_id = input('other_user_id');
        $other_user = Db::table('up_u_user')
            ->field('user_id, user_image, user_real_name, user_phone')
            ->where('user_id', $other_user_id)
            ->find();
        // 为我带来的总服务费
        $total = Db::table('up_bo_giftbag_integral')
            ->where('bgi_other_user_id', $other_user_id)
            ->where('bgi_user_id', $this->user_id)
            ->where('bgi_type', 1)
            ->sum('bgi_price');
        $other_user['get_total_balance'] = $total;
        return json(['status' => 200, 'msg' => $other_user]);
    }

    //***********************************************   礼包服务费  start  *********************************//

    /**
     * 用户服务费
     * @return \think\response\Json
     */
    public function myGiftBagFy(){
        // 总佣金
        $total_fy = Db::table('up_u_user')->where('user_id', $this->user_id)->value('user_giftbag_balance');
        // 不可提现佣金
        $unWithdraw = $this->unWithdraw();
        return json(['status' => 200, 'msg' => '', 'total_fy' => $total_fy, 'unWithdraw' => $unWithdraw]);
    }

    /**
     * 用户服务费详情
     * page         页码
     * type         0 全部    1 收入    2 支出
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fyList(){
        $type = input('type');
        $where['bgi_user_id'] = $this->user_id;
        if($type == 1){
            $where['bgi_type'] = 1;
        }elseif ($type == 2){
            $where['bgi_type'] = ['BETWEEN', [2, 3]];
        }
        $fy = Db::table('up_bo_giftbag_integral')
            ->where($where)
            ->field('bgi_number, bgi_desc, bgi_price, bgi_type, bgi_time')
            ->page($this->page, 10)
            ->order('bgi_time desc')
            ->select();
        if($fy){
            return json(['status' => 200, 'msg' => $fy]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 用户实名认证信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userAuth(){
        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_code, user_real_name')->find();
        return json(['status' => 200, 'msg' => $user]);
    }

    /**
     * 实名认证
     * real_name       真实姓名
     * user_card       身份证号
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateAuth(){
        $real_name = trim(input('real_name'), ' ');
        $user_card = trim(input('user_card'), ' ');

        // 身份证认证
        $check = $this->checkIdCard($real_name, $user_card);
        if($check['status'] == 0){
            return json($check);
        }

        $res = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->update(['user_real_name' => $real_name, 'user_code' => $user_card, 'user_update_time' => $this->create_time]);
        if($res){
            return json(['status' => 200, 'msg' => '认证成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }

    /**
     * 提现
     * type              提现方式    1 支付宝    2 微信
     * zh                提现账号
     * real_name         提现真实姓名
     * openid            微信提现openid
     * withdraw_price    提现金额
     * @return \think\response\Json
     */
    public function withdraw(){
        $type = input('type'); // 提现方式   1 支付宝    2 微信
        $zh = input('zh'); // 提现账号
        $real_name = input('real_name'); // 提现真实姓名
        $openid = input('openid'); // 微信提现openid
        $withdraw_price = input('withdraw_price'); // 提现金额

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);

//        $biz_no = 'BGW_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
//        $ali = new Ali(config('ali_tx'));
//        $tx = ['out_biz_no' => $biz_no, 'payee_account' => 15950506394, 'amount' => 0.1, 'payee_real_name' => '周洋'];
//        $return = $ali->aliTiXian($tx);
//        print_r($return);
//        die;

        if($withdraw_price <= 0){
            return json(['status' => 0, 'msg' => '请输入正确的提现金额']);
        }

        // 是否在可提现日期内
        $canTx = $this->canTxDate();
        if($canTx['can'] == 2){
            return json(['status' => 0, 'msg' => '每月' . $canTx['date'] . '日可提现']);
        }

        // 当日提现总数不可超过800
        $start = date('Y-m-d 00:00:00');
        $end = date('Y-m-d 23:59:59');
        $today_withdraw = Db::table('up_bo_giftbag_withdraw')
            ->where([
                'gw_user_id' => $this->user_id,
                'gw_time' => ['BETWEEN', [$start, $end]]
            ])
            ->sum('gw_price');
        if($withdraw_price + $today_withdraw > 796.8){
            return json(['status' => 0, 'msg' => "当日提现金额不可超过796.8元，已提现{$today_withdraw}元"]);
        }

        // 总佣金&身份证
        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_giftbag_balance, user_code')->find();
        // 不可提现佣金
        $unWithdraw = $this->unWithdraw();

//        print_r($unWithdraw);
        // 可提现金额
        $canWithdraw = $user['user_giftbag_balance'] - $unWithdraw;
//        print_r('--' . $withdraw_price . '--' . $canWithdraw);die;
        if(($withdraw_price > $canWithdraw) || $canWithdraw < 0){
            return json(['status' => 0, 'msg' => '可提现佣金不足']);
        }

        $biz_no = 'BGW_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        $withdraw = [
            'gw_user_id' => $this->user_id,
            'gw_price' => $withdraw_price,
            'gw_type' => $type,
            'gw_number' => $biz_no,
            'gw_zh' => $zh,
            'gw_time' => $this->create_time,
            'gw_real_name' => $real_name
        ];
        if($type == 2){
            $withdraw['gw_openid'] = $openid;
        }

        Db::startTrans();
        try{
            // 插入提现表
            Db::table('up_bo_giftbag_withdraw')->insert($withdraw);

            // 插入佣金明细
            insertBoGiftGagInte($this->user_id, 0, 2, '服务费提现', $withdraw_price, $user['user_giftbag_balance']);

            // 减礼包服务费
            Db::table('up_u_user')->where('user_id', $this->user_id)->update(['user_giftbag_balance' => $user['user_giftbag_balance'] - $withdraw_price]);

            // 提现
            if($type == 1){ // 支付宝提现
                $Ali = new Ali(config('ali_tx'));
                $tx = ['out_biz_no' => $biz_no, 'payee_account' => $zh, 'amount' => $withdraw_price, 'payee_real_name' => $real_name];
                $return = $Ali->aliTiXian($tx);
            }else{ // 微信提现

            }
            if($return['status'] == 200){
                Db::commit();
                return json(['status' => 200, 'msg' => '操作成功']);
            }else{
                Db::rollback();
                return json(['status' => 0, 'msg' => $return['msg']]);
            }
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }

    }

    //***********************************************   礼包服务费  end  *********************************//

    /**
     * 礼包规则
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function giftbagRule(){
        $data = Db::table('up_bo_giftbag_rule')->where('rule_id', 1)->field('rule_image, rule_content')->find();
        return json(['status' => 200, 'msg' => $data]);
    }


    //*********************************  公共方法
    /**
     * 判断是否可以购买礼包
     * @param $gift_id   礼包ID
     * @return int
     */
    public function canBuy($gift_id){
        $month = date('Y-m');
        $canBuy = 0; // 可以购买
    
        /**
         * 原需求为只可以有一个有效期内的礼包，现需求改为可以同时用多个有效期内的礼包
         */
        /*
        // 是否存在有效期内的礼包
        $indate = Db::table('up_bo_orderg')
            ->where(['bog_user_id' => $this->user_id, 'bog_indate' => ['>', $month], 'bog_is_pay' => 2])
            ->find();
        if($indate){
            $canBuy = 1; // 存在有效期内礼包，不可购买
        } else{
            $existThisGift = Db::table('up_bo_orderg')
                ->where(['bog_user_id' => $this->user_id, 'bog_indate' => ['<=', $month], 'bog_is_pay' => 2, 'bog_gift_id' => $gift_id])
                ->find();
            if($existThisGift){
                $canBuy = 2; // 已购买过该礼包，不可购买
            }
        }*/

        // 原需求
        // 1.已支付的订单不可重复购买
        $where = [
            'bog_user_id' => $this->user_id,
            'bog_gift_id' => $gift_id,
            'bog_is_pay' => 2
        ];
        $existThisGift = Db::table('up_bo_orderg')
            ->where($where)
            ->field('bog_is_pay, bog_status, bog_aftersale_status')
            ->find();
        if($existThisGift){
//            $canBuy = 2; // 已购买过该礼包，不可购买
            $canBuy = 0; // 需求改为不限制购买次数
        }
        return $canBuy;
    }
    
    /**
     * 默认快递公司
     * @return mixed
     */
    private function expressCompany(){
        return Db::table('up_about')->where('id', 7)->value('content');
    }
    
    /**
     * 我的礼包团队
     * @param int $type    1 列表    2 统计总积分
     * @param $my_invite   我的邀请码
     * @return false|float|int|\PDOStatement|string|\think\Collection
     */
    private function myTeam($type = 1, $my_invite){
        $query = Db::table('up_u_user')->where(['user_giftbag_invite_other' => $my_invite, 'user_status' => 1]);
        if($type == 1){ // 我的礼包团队列表
            $data = $query->field('user_id, user_real_name')
                ->order('user_time desc')
//                ->page($this->page, 10)
                ->select();
        }else{ // 我的礼包团队总计
            $data = $query->sum('user_bo_total_balance');
        }
        return $data;
    }

    /**
     * 是否是首次购买，不考虑售后，只要付钱了，就是购买过了，不可再享受首单减免
     * @param $gift_id
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function firstBuy($gift_id){
        $isFirst = Db::table('up_bo_orderg')->where(['bog_user_id' => $this->user_id, 'bog_gift_id' => $gift_id, 'bog_is_pay' => 2])->find();
        if($isFirst){
            return 1; // 非首次
        }else{
            return 2; // 首次
        }
    }

    /**
     * 不可提现的礼包分佣
     * @return float|int|string
     */
    private function unWithdraw(){
//        $limit = Db::table('up_bo_fy_config')->where('bfc_id', 9)->value('bfc_content');
//        $date = date('Y-m-d H:i:s', strtotime(" -{$limit} days"));
        // 本月第一天
        $first_day = date('Y-m-01 00:00:00');
        // 当前时间
        $now = date('Y-m-d H:i:s');

        $unWithdraw = Db::table('up_bo_giftbag_integral')
            ->where([
                'bgi_user_id' => $this->user_id,
                'bgi_type' => 1,
                'bgi_time' => ['BETWEEN', [$first_day, $now]]
            ])
            ->sum('bgi_price');
        return $unWithdraw;
    }
}